# -*- coding: utf-8 -*-

"""
Description: 运行程序
"""

import os
import json
import re
import time

from utils.file_operation import (
    load_json_to_dict,
    save_dict_to_json,
    generate_groups,
    excel_to_json_list,
)

from utils.picture import process_img
from rj.锐竞 import RJ_api
from rj.rjmart.pre_api_cx import pre_api_get
from ljk.index import RequestsHandler
import requests
from csm.basic import RequestHanlder
from utils.convert import header_placeholder, add_ad_service, footer_placeholder
from website.invivogen.index import process_product

# csm = RequestHanlder()
# rj = RJ_api()
# ol = pre_api_get()
# ljk = RequestsHandler()


def get_file_list(folder_path):
    """获取指定文件夹下所有文件列表

    Args:
        folder_path: 文件夹路径

    Returns:
        list: 文件路径列表
    """
    file_list = []
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file != ".DS_Store":
                # file_path = os.path.join(root, file)
                file_list.append(file)
    return file_list


def replace_img(photos: list, procode: str) -> list:
    img_base = f"https://ls-img-1316961827.cos.ap-guangzhou.myqcloud.com/photos/nest/{procode}.png"
    photos[0]["photo"] = img_base

    return photos


def download_image(url: str, filename: str, save_path: str = "./downloads"):
    """图片下载

    Args:
        url (str): 图片完整url
        filename (str): 文件名（商品货号）
        save_path (str, optional): 保存路径. Defaults to "./downloads".

    Raises:
        ValueError: _description_
    """
    response = requests.get(url, stream=True)
    if response.status_code == 200:
        # 获取 Content-Type
        content_type = response.headers.get("Content-Type")
        if not content_type or not content_type.startswith("image/"):
            raise ValueError("URL does not point to an image.")

        # 根据 Content-Type 推断扩展名
        ext = content_type.split("/")[-1]

        full_path = os.path.join(save_path, f"{filename}.{ext}")

        with open(full_path, "wb") as f:
            for chunk in response.iter_content(1024):
                f.write(chunk)
        print(f"Image saved as {full_path}")
    else:
        print(f"Failed to download image. Status code: {response.status_code}")


def process_img_url(img_str: str) -> str:
    img_base = "https://labgic-prd.oss-cn-hangzhou.aliyuncs.com"
    _temp_url = img_str.split(",")[0]
    if "http" in _temp_url:
        return _temp_url
    return img_base + _temp_url


def map_delivery_period(deliver_day):
    """
    货期格式映射

    1-7天
    兜底为-1,咨询客服

    Args:
        deliver_day (str): 货期

    Returns:
        int: 货期
    """
    deliver_dict = {"1": 101, "2": 102, "3": 103, "4": 104, "5": 105, "6": 106, "7": 7}
    return deliver_dict.get(deliver_day, -1)


def process_code(code_str: str):
    """处理商品编码

    Args:
        code_str (str): 商品编码

    Returns:
        str: 商品编码
    """
    _list = code_str.split("-")
    _len = len(_list)
    if _len > 1:
        procde: str = "-".join(_list[: _len - 1])
        return procde
    return code_str


def extract_value_unit(data):
    pattern = r"^([+-]?\d+(?:\.\d+)?)(\D+)$"  # 匹配开头为数字，后面为非数字的单位
    match = re.match(pattern, data.strip())

    if match:
        value_str = match.group(1)
        unit = match.group(2).strip()

        # 尝试将数值转为 float 或 int
        value = float(value_str) if "." in value_str else int(value_str)

        return {"value": value, "unit": unit}
    else:
        raise ValueError(f"无法解析输入数据: {data}")


# 使用示例
if __name__ == "__main__":
    ol = pre_api_get()
    # rj =RJ_api()
    # upload_list = load_json_to_dict("upload_list.json")
    # for group in generate_groups(upload_list, 50):
    #     res = ol.batchSaveOrUpdateProductV2(group)
    #     print(res.json())
    #     time.sleep(1)

    # total_list = load_json_to_dict("total_list_with_desc.json")
    # for item in total_list:
    #     print(item["productNum"])
    #     res = process_product(item["productNum"])
    #     if res:
    #         item["desc"] = res
    #         upload_list.append(item)
    #         time.sleep(1)
    # save_dict_to_json(upload_list, "upload_list.json")
    # print("done")

    # _temp_dict = {}
    # for item in total_list:
    #     code = process_code(item["spuCode"])
    #     res = _temp_dict.get(code, [])
    #     res.append(item)
    #     _temp_dict[code] = res
    # save_dict_to_json(_temp_dict, "total_dict.json")
    # print("done")